package com.aispeech.aicube;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.aispeech.aicube.voice.DDSService;
import com.aispeech.aicube.voice.observer.DuiUpdateObserver;
import com.aispeech.ailog.AILog;
import com.aispeech.dui.dds.DDS;
import com.aispeech.dui.dds.exceptions.DDSNotInitCompleteException;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class DuiSplashActivity extends Activity implements DuiUpdateObserver.UpdateCallback {

    private static final String TAG = "DuiSplashActivity";
    private static final int PERMISSION_REQUEST_CODE = 1283;
    private String[] BASE_PERMISSIONS = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
    };

    private AlertDialog mDialog;
    private int mAuthCount = 0;// 授权次数,用来记录自动授权

    private DuiUpdateObserver mUpdateObserver = new DuiUpdateObserver();// dds更新监听器

    private TextView mTvInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dui);
        mTvInfo = findViewById(R.id.tv_splash_info);

        if (!isAllPermissionsGrant()) {
            requestAllPermission();
        } else {
            initDDS();
        }
    }

    private void requestAllPermission() {
        ActivityCompat.requestPermissions(this, BASE_PERMISSIONS, PERMISSION_REQUEST_CODE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 注册一个广播,接收service中发送的dds初始状态广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("ddsdemo.intent.action.auth_success");// 认证成功的广播
        intentFilter.addAction("ddsdemo.intent.action.auth_failed");// 认证失败的广播
        intentFilter.addAction("ddsdemo.intent.action.init_complete");// 语音初始化完成广播
        registerReceiver(authReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 释放注册的广播
        unregisterReceiver(authReceiver);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }

        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "Permission \"" + permissions[i] + "\" denied. Using its associated features will not be possible!");
                    requestAllPermission();
                    return;
                }
            }

            if (isAllPermissionsGrant()) {
                initDDS();
            }
        }
        Log.d(TAG, "All permissions accepted!");
    }

    private boolean isAllPermissionsGrant() {
        boolean grant = isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE) &&
                isPermissionGranted(Manifest.permission.CAMERA) &&
                isPermissionGranted(Manifest.permission.RECORD_AUDIO) &&
                isPermissionGranted(Manifest.permission.READ_PHONE_STATE);
        Log.d(TAG, "isAllPermissionsGrant: " + grant);
        return grant;
    }

    private boolean isPermissionGranted(String permissionId) {
        return ContextCompat.checkSelfPermission(getBaseContext(), permissionId) == PackageManager.PERMISSION_GRANTED;
    }

    private void initDDS() {
        startService(new Intent(this, DDSService.class));
        new Thread() {
            public void run() {
                checkDDSReady();
            }
        }.start();
    }

    // 检查dds是否初始成功
    public void checkDDSReady() {
        while (true) {
            try {
//                if (DDS.getInstance().getInitStatus() == DDS.INIT_COMPLETE_FULL ||
//                        DDS.getInstance().getInitStatus() == DDS.INIT_COMPLETE_NOT_FULL) {
                if (DDS.getInstance().getInitStatus() == DDS.INIT_COMPLETE_FULL) {


                    if (DDS.getInstance().isAuthSuccess()) {
//                        gotoVoiceActivity();
                        gotoLiveActivity();
                        break;
                    } else {
                        // 自动授权
                        doAutoAuth();
                    }
                    break;
                } else if (DDS.getInstance().getInitStatus() == DDS.INIT_COMPLETE_NOT_FULL) {
                    mUpdateObserver.regist(this);
                } else {
                    AILog.w(TAG, "waiting  init complete finish...");
                }

                Thread.sleep(800);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    // 跳转到主页面
//    private void gotoVoiceActivity() {
//        Log.d(TAG, "gotoVoiceActivity: ");
//        Intent intent = new Intent(getApplicationContext(), VoiceActivity.class);
//        startActivity(intent);
//        finish();
//    }

    // 跳转到直播页面
    private void gotoLiveActivity() {
        Intent intent = new Intent(getApplicationContext(), LiveDetectionActivity.class);
        startActivity(intent);
        finish();
    }

    // 显示授权弹框给用户
    private void showDoAuthDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(DuiSplashActivity.this);
                builder.setMessage("未授权");
                builder.setPositiveButton("做一次授权", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        try {
                            DDS.getInstance().doAuth();
                        } catch (DDSNotInitCompleteException e) {
                            e.printStackTrace();
                        }
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.dismiss();
                        finish();
                    }
                });

                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
                mDialog = builder.create();
                mDialog.show();
            }
        });
    }

    // 认证广播
    private BroadcastReceiver authReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TextUtils.equals(intent.getAction(), "ddsdemo.intent.action.auth_success")) {
//                gotoVoiceActivity();
                gotoLiveActivity();
            } else if (TextUtils.equals(intent.getAction(), "ddsdemo.intent.action.auth_failed")) {
                doAutoAuth();
            } else if (TextUtils.equals(intent.getAction(), "ddsdemo.intent.action.init_complete")) {
                Log.d(TAG, "onReceive: init_complete");
            }
        }
    };

    // 执行自动授权
    private void doAutoAuth() {
        // 自动执行授权5次,如果5次授权失败之后,给用户弹提示框
        if (mAuthCount < 5) {
            try {
                DDS.getInstance().doAuth();
                mAuthCount++;
            } catch (DDSNotInitCompleteException e) {
                e.printStackTrace();
            }
        } else {
            showDoAuthDialog();
        }
    }

    @Override
    public void onUpdate(int type, final String result) {
//        Log.d(TAG, "onUpdate() called with: type = [" + type + "], result = [" + result + "]");
        DuiSplashActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTvInfo.setText(result);
            }
        });
        if ("更新成功".equals(result)) {
            if (null != mUpdateObserver) {
                mUpdateObserver.unregist();
            }
        }
    }
}
